package com.sky.wsp.captcha;

import com.wf.captcha.SpecCaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @desccription 测试EasyCaptcha内存泄露
 * @auth wangshaopeng@talkweb.com.cn
 * @date 2022/9/9
 */
@RestController
@RequestMapping("test")
public class TestController {
    Logger log = LoggerFactory.getLogger(TestController.class);
    Font font;
    {
        try {
            font = Font.createFont(0, this.getClass().getResourceAsStream("/actionj.ttf")).deriveFont(1, 32.0F);
        } catch (FontFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 每次创建验证码时，都重新加载字体文件，会导致OOM
     *
     * @param p
     * @return
     */
    @GetMapping("/c1")
    public Map<String, String> captcha1(String p) {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        log.info("c1 captcha verCode:{}, p:{}", verCode, p);
        // 将key和base64返回给前端
        Map<String, String> map = new HashMap<>(2);
        map.put("verCode", verCode);
        map.put("image", specCaptcha.toBase64());
        return map;
    }

    /**
     * 使用全局字体对象，只加载一次字体文件，避免OOM
     *
     * @param p
     * @return
     */
    @GetMapping("/c2")
    public Map<String, String> captcha2(String p) {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        specCaptcha.setFont(font);
        String verCode = specCaptcha.text().toLowerCase();
        log.info("c2 captcha verCode:{}, p:{}", verCode, p);
        // 将key和base64返回给前端
        Map<String, String> map = new HashMap<>(2);
        map.put("verCode", verCode);
        map.put("image", specCaptcha.toBase64());
        return map;
    }

}
